package com.zjht.gmcc.bean.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class LogUtil {

	// 错误代码
	public static final String ERRCODE_SEVRLET_SYS = "00";// SEVRLET系统异常错误
	public static final String ERRCODE_SEVRLET_USER = "01";// SEVRLET逻辑异常错误
	public static final String ERRCODE_JSP_SYS = "10";// JSP系统异常错误
	public static final String ERRCODE_JSP_USER = "11";// JSP逻辑异常错误

	// 错误来源
	public static final int ERRSOURCE_SERVLET = 0;
	public static final int ERRSOURCE_JSP = 1;

	// 错误类型
	public static final int ERRTYPE_SYS = 0;// 系统错误
	public static final int ERRTYPE_USER = 1;// 用户逻辑错误

	/**
	 * 获取错误代码
	 * @param errSource 错误来源
	 * @param errType 错误类型
	 * @param menuid
	 * @return 错误编码(含菜单ID)
	 */
	public static String getErrCode(int errSource, int errType, String menuid) {
		String errPrefix = "";
		switch (errSource) {
			case ERRSOURCE_SERVLET:
				switch (errType) {
					case ERRTYPE_SYS:
						errPrefix = ERRCODE_SEVRLET_SYS;
						break;
					case ERRTYPE_USER:
						errPrefix = ERRCODE_SEVRLET_USER;
						break;
				}
				break;
			case ERRSOURCE_JSP:
				switch (errType) {
					case ERRTYPE_SYS:
						errPrefix = ERRCODE_JSP_SYS;
						break;
					case ERRTYPE_USER:
						errPrefix = ERRCODE_JSP_USER;
						break;
				}
				break;
		}
		return errPrefix + "#" + (menuid != null && menuid.length() > 0 ? menuid : "");
	}

	/**
	 * 系统发生JSP或Servlet异常时记录错误日志
	 * @author dyh 2009-11-15
	 * @param request
	 * @param errcode 错误代码：错误前缀+menuid
	 */
	public static void logErr(HttpServletRequest request, String errcode) {
		try {
			StringBuilder err = new StringBuilder();
			err.append("errcode=");
			err.append(errcode);
			if (request != null) {
				HttpSession session = request.getSession();
				if (session != null) {
					err.append(",orgcode=");
					err.append(MySession.getOrgcode(session));
					err.append(",orgname=");
					err.append(MySession.getOrgname(session));
					err.append(",orgtypeid=");
					err.append(MySession.getOrgtype(session));
					err.append(",usercode=");
					err.append(MySession.getUsercode(session));
					err.append(",username=");
					err.append(MySession.getUsername(session));
				}
			}
			System.err.println(err);
			System.err.println();
		} catch (Exception e) {
			System.err.println("LogUtil.logErr error");
		}
	}
}
